package Util;

import com.newsproject.pojo.User;
import lombok.Getter;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

public class SessionUtils {

    public enum SessionType{
        ADMIN,TAG
    }

    public static void checkAdminSession(HttpSession session) {
        checkSession(session, SessionType.ADMIN, null);
    }
    public static void checkTagSession(HttpSession session) {
        checkSession(session, SessionType.TAG, null);
    }
    //统一会话检查方法
    public static void checkSession(HttpSession session, SessionType type, RedirectAttributes redirectAttributes) {
        try{
            switch(type){
                case ADMIN:
                    validateAdminSession(session);
                    break;
                case TAG:
                    validateTagSession(session);
                    break;
            }
        }  catch (SessionCheckException e){
            if(redirectAttributes != null){
                redirectAttributes.addFlashAttribute(SessionCheckException.getErrorAttribute(type),e.getMessage());
            }
            throw e;
        }

    }
     //验证逻辑分离
     private static void validateAdminSession(HttpSession session){
        User user = (User) session.getAttribute("userInfo");
        if(user == null || user.getAdminStatus() != 1){
            throw new SessionCheckException("redirect:/user/login", "管理员会话已过期，请重新登录");
        }
     }
     private static void validateTagSession(HttpSession session){
        Object tagId =  session.getAttribute("tagId");
        if(!(tagId instanceof Integer)) {
            throw new SessionCheckException("redirect:/AdminController/audit", "类别参数有误");
        }
     }

    @Getter
    public static class SessionCheckException extends RuntimeException{
        private final String redirectUrl;
        private final String errorMessage;

        public SessionCheckException(String redirectUrl, String errorMessage) {
            super(errorMessage);
            this.redirectUrl = redirectUrl;
            this.errorMessage = errorMessage;
        }

        private static String getErrorAttribute(SessionType type){
            return type == SessionType.ADMIN ? "error" : "TagError";
     }

    }

}

